﻿#include "openglwindow.h"
#include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLPaintDevice>
#include <QtGui/QPainter>

Openglwindow::Openglwindow(QWindow *parent)
    :QWindow(parent)
    ,m_animating(false)
    ,m_context(0)
    ,m_device(0)
{
    //设置使用OpenGL上下文渲染OpenGL
    setSurfaceType(QWindow::OpenGLSurface);
}
Openglwindow::~Openglwindow()
{
    //删除设备
    delete m_device;
}
void Openglwindow::render(QPainter *painter)
{
    Q_UNUSED(painter);
}

void Openglwindow::initialize()
{
}
void Openglwindow::render()
{
    //第一次没有画笔设备，需要创建画笔设备
    if (!m_device)
        m_device = new QOpenGLPaintDevice;

    //清除屏幕， 颜色缓冲区和深度缓冲区和模板缓冲区
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    //设置大小
    m_device->setSize(size());

    //创建画笔
    QPainter painter(m_device);
    //用QPainter渲染一次
    render(&painter);
}
void Openglwindow::renderLater()
{
    //请求刷新，窗口会收到UpdateRequest事件
    requestUpdate();
}
bool Openglwindow::event(QEvent *event)
{
    switch (event->type()) {
    case QEvent::UpdateRequest:
        renderNow();
        return true;
    default:
        return QWindow::event(event);
    }
}
void Openglwindow::exposeEvent(QExposeEvent *event)
{
    Q_UNUSED(event);

    //如果窗口暴露，显示，立刻渲染画面
    if (isExposed())
        renderNow();
}
void Openglwindow::renderNow()
{
    if (!isExposed())
        return;

    bool needsInitialize = false;

    //没有上下文就创建上下文
    if (!m_context) {
        m_context = new QOpenGLContext(this);
        //设置格式
        m_context->setFormat(requestedFormat());
        //创建
        m_context->create();

        needsInitialize = true;
    }

    //激活上下文
    m_context->makeCurrent(this);

    if (needsInitialize) {
        //初始化当前上下文的OpenGL函数解析
        initializeOpenGLFunctions();
        initialize();
    }

    render();

    //交换前后缓冲区，完成一帧渲染
    m_context->swapBuffers(this);

    if (m_animating)
        renderLater();
}
void Openglwindow::setAnimating(bool animating)
{
    m_animating = animating;

    if (animating)
        renderLater();
}
